
package io.dbw.modules.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.dbw.common.enums.ResultStatusEnum;
import io.dbw.common.exception.BusinessException;
import io.dbw.common.utils.*;
import io.dbw.modules.business.dao.SysMenuDao;
import io.dbw.modules.business.dao.SysUserDao;
import io.dbw.modules.business.entity.SysMenuEntity;
import io.dbw.modules.business.entity.SysUserEntity;
import io.dbw.modules.business.form.StoreLoginForm;
import io.dbw.modules.business.form.SysLoginForm;
import io.dbw.modules.business.service.*;
import io.dbw.modules.business.vo.CommonUserVO;
import io.dbw.modules.business.vo.LoginUserVO;
import io.dbw.modules.business.vo.MenuVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 系统用户
 *
 * 
 */
@Slf4j
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Resource
	private SysUserRoleService sysUserRoleService;

	@Resource
	private SysRoleService sysRoleService;

	@Resource
	private SysMenuDao sysMenuDao;

	@Resource
	private SysUserTokenService sysUserTokenService;

	@Resource
	private SysCaptchaService sysCaptchaService;

    @Resource
    private RedisUtils redisUtils;

	@Value("${spring.profiles.active}")
	private String active;

	@Value("${common.systemCompany}")
	private String systemCompany;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {

		Integer pageNo= MapUtils.getInteger(params,"pageNo",1);
		Integer pageSize= MapUtils.getInteger(params,"pageSize",10);
		Page page = new Page<>(pageNo, pageSize);

		List<SysUserEntity> list =  baseMapper.queryUserPage(page,params);
		page.setRecords(list);
		return new PageUtils(page);
	}

	@Override
	public List<String> queryAllPerms(Long userId ) {
		return baseMapper.queryAllPerms(userId );
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String userName) {
		return baseMapper.queryByUserName(userName);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUser(SysUserEntity user) {

		user.setStatus(Constant.SYSTEM_COMMON_ONE);
		CommonUserVO c =ShiroUtils.getCommonUserVO();
		user.setCreateBy(c.getUserId());
		user.setCreateTime(new Date());
		this.save(user);
		List<Long> roleIdList=Arrays.asList(2L);
		if(Constant.SYSTEM_COMMON_Y.equals(user.getManagerFlag()) ){
			roleIdList=Arrays.asList(3L);
		}
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), roleIdList);

	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateUser(SysUserEntity user) {
		//检查角色是否越权
//		checkRole(user);
		this.updateById(user);
		//保存用户与角色关系
		if(user.getRoleEditFlag()){
			List<Long> roleIdList=Arrays.asList(2L);
			if(Constant.SYSTEM_COMMON_Y.equals(user.getManagerFlag()) ){
				roleIdList=Arrays.asList(3L);
			}
			sysUserRoleService.saveOrUpdate(user.getUserId(), roleIdList);
		}
	}

	@Override
	public void deleteBatch(List<Long> list) {
		this.removeByIds(list);
	}

	@Override
	public boolean updatePassword(Long userId, String newPassword) {
		return this.update(Wrappers.<SysUserEntity>lambdaUpdate()
				.set(SysUserEntity::getPassword,newPassword)
				.eq(SysUserEntity::getUserId, userId));
	}
	
	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user){

		CommonUserVO commonUserVO =ShiroUtils.getCommonUserVO();
		Long userId=commonUserVO.getUserId();
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if( userId.equals(Constant.SUPER_ADMIN)){
			return ;
		}
		List<Long> userRoleIdList ;
			userRoleIdList=user.getRoleIdList();
		//查询用户创建用户的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(userId);

		//判断是否越权
		if(!roleIdList.containsAll(userRoleIdList)){
			throw new BusinessException("所选用户角色越权,请联系管理员");
		}
	}

	@Override
	public List<SysMenuEntity> queryAllPermsByUserId(Long userId ) {
        if(userId.equals(Constant.SUPER_ADMIN)) {
            return sysMenuDao.selectList(new QueryWrapper<SysMenuEntity>().eq("visible",1));
        }
		return baseMapper.queryAllPermsByUserId(userId );
	}

	/**
	 * 账号登录
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@Override
	public Result login(SysLoginForm form ) throws Exception{
		if (StringUtils.isNotBlank(active)&& "prod".equals(active)){
			String code = StringUtil.toString(redisUtils.get(Constant.CAPTCHA_CODE + form.getUuid()));
			if(StringUtils.isBlank(code) || !code.equals(form.getCaptcha())){
				return Result.info(ResultStatusEnum.INVALID_CAPTCHA_ERROR);
			}
//			boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
//			if(!captcha){
//				return Result.info(ResultStatusEnum.INVALID_CAPTCHA_ERROR);
//			}

		}
		//用户信息
		SysUserEntity user = baseMapper.queryByUserName(form.getUserName().trim());
		//密码错误
		if(null==user){
			return Result.info(ResultStatusEnum.USER_ERROR);
		}
		if(!user.getPassword().trim().equals(form.getPassword().trim())) {
			return Result.info(ResultStatusEnum.USER_PASSWORD_ERROR);
		}
		//账号锁定
		if(user.getStatus() == 0){
			return Result.info(ResultStatusEnum.USER_FROZEN);
		}
		LoginUserVO loginUserVO = getLoginUserVO(user);
		redisUtils.del(Constant.CAPTCHA_CODE + form.getUuid());
		return Result.success(loginUserVO);
	}

	@Override
	public Result mobileLogin(StoreLoginForm form ) throws Exception{
		if (StringUtils.isNotBlank(active)  ){
			if(!form.getValidCode().equals("000000")){
				return Result.info(ResultStatusEnum.INVALID_CAPTCHA_ERROR);
			}
		}
		//用户信息
		SysUserEntity user = baseMapper.selectOne(new QueryWrapper<SysUserEntity>()
				.eq("mobile",form.getMobile())
				.like("user_type",Constant.USER_TYPE_STORE)
				.like("delete_flag",Constant.SYSTEM_COMMON_N)
		);
		//账号不存在 或者 密码错误
		if(user == null) {
			return Result.info(ResultStatusEnum.USER_ERROR);
		}
		//账号锁定
		if(user.getStatus() == 0){
			return Result.info(ResultStatusEnum.USER_FROZEN);
		}
		return Result.success(getLoginUserVO(user));
	}

	private LoginUserVO getLoginUserVO(SysUserEntity user) throws Exception{
		//生成token，并保存到数据库
		Long userId=user.getUserId();
		LoginUserVO loginUserVO = sysUserTokenService.createToken(userId );
		user.setPassword(null);
		loginUserVO.setUserInfo(user);
		List<SysMenuEntity> menuList;
		if(userId.equals(Constant.SUPER_ADMIN)) {
			menuList = sysMenuDao.selectList(new QueryWrapper<SysMenuEntity>().eq("visible",1));
		}else{
			menuList =baseMapper.queryAllPermsByUserId(userId );
		}
		List<SysMenuEntity> mList=menuList.stream().filter(m->(m.getType()!=2)).collect(Collectors.toList());
		if(CollectionUtils.isNotEmpty(mList)){
			//去重复，构建树形和排序
			List<MenuVO> rmList = ListUtils.getMenuList(ListUtils.removeDuplicateDept(mList),2)
					.stream().sorted(Comparator.comparing(MenuVO::getOrderNum)).collect(Collectors.toList());
			//暂时隐藏平台端(非银行用户)-数据中心
			List<MenuVO> meList = new ArrayList<>();
			loginUserVO.setListMenu(rmList);
		}
		List<String> permsList=menuList.stream().filter(m->(m.getType()==2)).map(m-> m.getPerms()).collect(Collectors.toList());
		loginUserVO.setPermsList(permsList);
		return loginUserVO;
	}

}